package com.fary.web.servlet.mvc.method.annotation;

import com.fary.core.MethodParameter;
import com.fary.web.context.request.NativeWebRequest;
import com.fary.web.context.request.async.WebAsyncUtils;
import com.fary.web.method.support.HandlerMethodReturnValueHandler;
import com.fary.web.method.support.ModelAndViewContainer;

import java.util.concurrent.Callable;

public class CallableMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return Callable.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        if (returnValue == null) {
            mavContainer.setRequestHandled(true);
            return;
        }

        Callable<?> callable = (Callable<?>) returnValue;
        WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
    }

}